#include "logger.h"
//#include "usart.h"
#include "usbd_cdc_if.h"
#include <stdio.h>
#include <stdarg.h>

uint8_t block_flag = 0;
uint8_t lprocess_flag = 0;
uint8_t lcommand_flag = 1;

extern uint8_t UserTxBufferFS[];
extern USBD_HandleTypeDef hUsbDeviceFS;

#if 0
#ifdef __GNUC__
#define PUTCHAR_PROTOTYPE int __io_putchar(int ch)
#else
#define PUTCHAR_PROTOTYPE int fputc(int ch, FILE *f)
#endif /* __GNUC__ */

PUTCHAR_PROTOTYPE
{
    //HAL_UART_Transmit(&LOG_UART_HANDLE, (uint8_t *)&ch, 1, HAL_MAX_DELAY);
    if( hUsbDeviceFS.dev_state == USBD_STATE_CONFIGURED )
    {
        uint8_t rc;
        do {
            rc = CDC_Transmit_FS((uint8_t *)&ch, 1);
        }while (USBD_BUSY == rc);
    }
    return ch;
}
#else
#ifdef __GNUC__
int _write(int file, const char* data, int len)
{
    if( hUsbDeviceFS.dev_state == USBD_STATE_CONFIGURED )
    {
        uint8_t rc;
        do {
            rc = CDC_Transmit_FS((uint8_t *)data, len);
        }while (USBD_BUSY == rc);
    }
    return len;
}
#endif
#endif

void usb_printf(const char *format, ...)
{
    va_list args;
    uint32_t length;
    va_start(args, format);
    length = vsnprintf((char *)UserTxBufferFS, APP_TX_DATA_SIZE, (char *)format, args);
    va_end(args);
    if( hUsbDeviceFS.dev_state == USBD_STATE_CONFIGURED ){
		uint8_t rc;
		do {
			rc = CDC_Transmit_FS(UserTxBufferFS, length);
		}while (USBD_BUSY == rc);
	}
}

void log_dump(const uint8_t *data, uint16_t len)
{
    uint8_t ch, cl;
    for (int i = 0; i < len; i++) {
        ch = data[i] >> 4;
        cl = data[i] & 0x0F;
        if (ch < 10) ch += '0'; else ch += 'A' - 10;
        if (cl < 10) cl += '0'; else cl += 'A' - 10;
        log_printf("%c%c",ch, cl);
        log_printf(" ");
        if ((i + 1) % 16 == 0) {
            log_printf("\r\n");
        } else if ((i + 1) % 8 == 0) {
            ch = ' ';
            log_printf("%c%c%c%c",ch, ch, ch, ch);
        } else {
            ch = ' ';
            log_printf("%c",ch);
        }
    }
    log_printf("\r\n");
}

void log_test()
{
	LOG_INFO("Hello World!, age=%d", 99);
    LOG_DEBUG("Hello Debug!, age=%d", 99);
	LOG_ERROR("Log Error, age=%d", 99);
	LOG_ERROR2();
	LOG_ERROR3(1);
	LOG_ERROR3(0);
	LOG_ASSERT(1);
	LOG_ASSERT(0);
	LOG_DUMP("log dump", (const uint8_t*)"Mike is a good man!",25);
}
